from fastapi import APIRouter, HTTPException, Depends, File, UploadFile, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Optional, Dict
import datetime
import random
import os
from pathlib import Path

from commons.database import Database
from DAL.order import Order, OrderItem
from DAL.product import Product
from DAL.user import User

# 创建API路由
router = APIRouter(prefix='/api', tags=['order'])

# Pydantic模型定义
class OrderItemCreate(BaseModel):
    product_id: int
    quantity: int

class OrderCreate(BaseModel):
    seller_id: int
    items: List[OrderItemCreate]
    contact_info: str

class OrderUpdate(BaseModel):
    status: Optional[int] = None
    logistics_info: Optional[str] = None

class OrderItemResponse(BaseModel):
    id: int
    product_id: int
    quantity: int
    price: float
    product_name: Optional[str] = None
    product_image: Optional[str] = None

class OrderResponse(BaseModel):
    id: int
    buyer_id: int
    seller_id: int
    status: int
    total_amount: float
    payment_proof: Optional[List[str]] = None
    logistics_info: Optional[str] = None
    contact_info: str
    created_at: datetime.datetime
    updated_at: datetime.datetime
    items: List[OrderItemResponse]

    class Config:
        from_attributes = True

# 辅助函数：获取数据库会话
def get_db():
    db = next(Database.get_db())
    try:
        yield db
    finally:
        db.close()

# 辅助函数：生成唯一文件名
def generate_filename(ext: str) -> str:
    date_part = datetime.datetime.now().strftime("%Y%m%d")
    time_part = datetime.datetime.now().strftime("%H%M%S") + f"{random.randint(0, 99):02d}"
    return f"{date_part}_{time_part}{ext.lower()}"

# 创建订单接口
@router.post("/orders", response_model=OrderResponse)
def create_order(
    order_data: OrderCreate,
    buyer_id: int,
    db: Session = Depends(get_db)
):
    """
    创建新订单
    需要买家ID和订单商品列表
    """
    # 验证买家是否存在
    buyer = db.query(User).filter(User.id == buyer_id).first()
    if not buyer:
        raise HTTPException(status_code=404, detail="买家不存在")

    # 验证卖家是否存在
    seller = db.query(User).filter(User.id == order_data.seller_id).first()
    if not seller or not seller.is_approved:
        raise HTTPException(status_code=404, detail="卖家不存在或未通过审核")

    # 验证订单项并计算总金额
    total_amount = 0.0
    order_items = []
    for item_data in order_data.items:
        product = db.query(Product).filter(
            Product.id == item_data.product_id, 
            Product.seller_id == order_data.seller_id, 
            Product.is_active == True
        ).first()
        if not product:
            raise HTTPException(status_code=404, detail=f"商品 {item_data.product_id} 不存在或未上架")
        if item_data.quantity <= 0:
            raise HTTPException(status_code=400, detail="商品数量必须大于0")

        item_total = product.price * item_data.quantity
        total_amount += item_total
        order_items.append(OrderItem(
            product_id=item_data.product_id,
            quantity=item_data.quantity,
            price=product.price
        ))

    # 创建订单
    db_order = Order(
        buyer_id=buyer_id,
        seller_id=order_data.seller_id,
        total_amount=total_amount,
        contact_info=order_data.contact_info,
        items=order_items
    )
    db.add(db_order)
    db.commit()
    db.refresh(db_order)
    return db_order

# 获取订单列表接口
@router.get("/orders", response_model=List[OrderResponse])
def get_orders(
    user_id: int,
    user_type: str = Query(..., enum=["buyer", "seller"]),
    status: Optional[int] = None,
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db)
):
    """
    获取订单列表
    user_type: buyer-买家订单, seller-卖家订单
    status: 可选，订单状态筛选
    """
    query = db.query(Order)
    if user_type == "buyer":
        query = query.filter(Order.buyer_id == user_id)
    elif user_type == "seller":
        query = query.filter(Order.seller_id == user_id)
    else:
        raise HTTPException(status_code=400, detail="无效的用户类型")

    if status is not None:
        query = query.filter(Order.status == status)

    return query.order_by(Order.created_at.desc()).offset(skip).limit(limit).all()

# 获取单个订单接口
@router.get("/orders/{order_id}", response_model=OrderResponse)
def get_order(order_id: int, user_id: int, db: Session = Depends(get_db)):
    """
    获取单个订单详情
    只能获取自己的订单（买家或卖家）
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")

    # 验证权限（买家或卖家）
    if order.buyer_id != user_id and order.seller_id != user_id:
        raise HTTPException(status_code=403, detail="没有权限查看此订单")

    return order

# 更新订单状态接口
@router.put("/orders/{order_id}/status", response_model=OrderResponse)
def update_order_status(
    order_id: int,
    user_id: int,
    status: int,
    user_type: str = Query(..., enum=["buyer", "seller"]),
    db: Session = Depends(get_db)
):
    """
    更新订单状态
    buyer只能更新为已付款状态
    seller只能更新为已发货或已取消状态
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")

    # 验证权限和状态转换合法性
    if user_type == "buyer":
        if order.buyer_id != user_id:
            raise HTTPException(status_code=403, detail="没有权限更新此订单")
        # 买家只能将订单状态从待付款(0)更新为已付款(1)
        if order.status != 0 or status != 1:
            raise HTTPException(status_code=400, detail="买家只能将待付款订单更新为已付款状态")
    elif user_type == "seller":
        if order.seller_id != user_id:
            raise HTTPException(status_code=403, detail="没有权限更新此订单")
        # 卖家只能将订单状态从已付款(1)更新为已发货(2)或已取消(4)
        if order.status != 1 or status not in [2, 4]:
            raise HTTPException(status_code=400, detail="卖家只能将已付款订单更新为已发货或已取消状态")
    else:
        raise HTTPException(status_code=400, detail="无效的用户类型")

    # 更新订单状态
    order.status = status
    db.commit()
    db.refresh(order)
    return order

# 上传付款凭证接口
@router.post("/orders/{order_id}/payment-proof", response_model=Dict)
async def upload_payment_proof(
    order_id: int,
    buyer_id: int,
    files: List[UploadFile] = File(...),
    db: Session = Depends(get_db)
):
    """
    上传付款凭证图片
    只能由买家上传，最多5张图片
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    if order.buyer_id != buyer_id:
        raise HTTPException(status_code=403, detail="没有权限上传付款凭证")
    if order.status != 0:
        raise HTTPException(status_code=400, detail="只能为待付款订单上传付款凭证")
    if len(files) > 5:
        raise HTTPException(status_code=400, detail="最多只能上传5张图片")

    # 上传图片
    allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif'}
    file_paths = []
    upload_dir = Path("uploads/payment_proofs")
    upload_dir.mkdir(parents=True, exist_ok=True)

    for file in files:
        ext = os.path.splitext(file.filename)[1].lower()
        if ext not in allowed_extensions:
            raise HTTPException(status_code=400, detail=f"不支持的图片格式: {ext}")

        filename = generate_filename(ext)
        file_path = str(upload_dir / filename).replace('\\', '/')
        with open(file_path, "wb+") as file_object:
            file_object.write(await file.read())
        file_paths.append(file_path)

    # 更新订单付款凭证
    order.payment_proof = file_paths
    order.status = 1  # 自动更新为已付款状态
    db.commit()

    return {"message": "付款凭证上传成功", "file_paths": file_paths}

# 更新物流信息接口
@router.put("/orders/{order_id}/logistics", response_model=OrderResponse)
def update_logistics_info(
    order_id: int,
    seller_id: int,
    logistics_info: str,
    db: Session = Depends(get_db)
):
    """
    更新订单物流信息
    只能由卖家更新
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    if order.seller_id != seller_id:
        raise HTTPException(status_code=403, detail="没有权限更新此订单")
    if order.status != 2:
        raise HTTPException(status_code=400, detail="只能为已发货订单更新物流信息")

    order.logistics_info = logistics_info
    db.commit()
    db.refresh(order)
    return order

# 买家确认收货接口
@router.post("/orders/{order_id}/confirm", response_model=OrderResponse)
def confirm_receipt(
    order_id: int,
    buyer_id: int,
    db: Session = Depends(get_db)
):
    """
    买家确认收货
    将订单状态更新为已完成(3)
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    if order.buyer_id != buyer_id:
        raise HTTPException(status_code=403, detail="没有权限确认此订单")
    if order.status != 2:
        raise HTTPException(status_code=400, detail="只能确认已发货状态的订单")

    order.status = 3  # 已完成状态
    db.commit()
    db.refresh(order)
    return order